package mark.tom.sail;

import androidx.annotation.NonNull;

import java.util.Map;

import static mark.tom.sail.Util.log_d;
import static mark.tom.sail.Util.log_i;

class DefaultAnalyticsCollector extends AnalyticsCollector {

    // 日志数据网络上报器
    private final RecordCollector mLogRecordCollector;

    DefaultAnalyticsCollector(String mIdKey,
                              DataConverter mLogDataConvert,
                              FileGenerator mLogFileGenerator,
                              FileStorage mLogFileStorage,
                              DataSecurity mLogDataSecurity,
                              LogInterceptor logInterceptor,
                              RecordCollector recordCollector) {
        super(mIdKey, mLogDataConvert, mLogFileGenerator, mLogFileStorage, mLogDataSecurity, logInterceptor);
        this.mLogRecordCollector = recordCollector;
    }

    @Override
    void collectLog(@NonNull String tag, @NonNull Map<String, Object> data) throws Exception {
        // 检查各项控制器
        if (!checkConfiguration()) {
            throw new IllegalArgumentException();
        }
        // 检查入参的正确性
        if (tag.trim().length() == 0 || data.isEmpty()) {
            throw new NullPointerException();
        }
        log_i(mLogInterceptor, "=====================Analytics Collect Begin============================");
        log_d(mLogInterceptor, "Raw Map Is : " + data.toString());
        String convertStr = mLogDataConvert.convert(data);
        log_d(mLogInterceptor, "Converted String Is : " + convertStr);
        // 转换Map数据为String并进行数据加密
        String encryptStr = mLogDataSecurity.encrypt(convertStr);
        log_d(mLogInterceptor, "Encrypted String Is : " + encryptStr);
        if (encryptStr == null || encryptStr.trim().length() == 0) {
            throw new RuntimeException();
        }
        // 生成文件名称
        String generatorFileName = mLogFileGenerator.generate(tag, mIdKey);
        log_d(mLogInterceptor, "Generator FileName Is : " + generatorFileName);
        if (generatorFileName == null || generatorFileName.trim().length() == 0) {
            throw new RuntimeException();
        }
        // 存储日志 (后台进程处理)
        mLogRecordCollector.doInBackground(generatorFileName, encryptStr, mLogFileStorage, mLogInterceptor);
        log_i(mLogInterceptor, "=====================Analytics Collect End============================");
    }
}
